package com.ts.api.module.match.market.internal.executor.handler;

import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Empty;
import com.gitee.apanlh.util.id.IdUtils;
import com.gitee.apanlh.util.log.Log;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.common.context.ChannelUserContext;
import com.ts.api.module.channel.entity.ChannelRequest;
import com.ts.api.module.channel.entity.cache.ChannelCacheUser;
import com.ts.api.module.channel.entity.po.ChannelMarketPO;
import com.ts.api.module.channel.entity.po.ChannelUserFormFieldPO;
import com.ts.api.module.channel.entity.po.ChannelUserRegisterPO;
import com.ts.api.module.channel.entity.qo.ChannelUserQO;
import com.ts.api.module.channel.service.ChannelFormService;
import com.ts.api.module.channel.service.ChannelLoginService;
import com.ts.api.module.channel.service.ChannelUserService;
import com.ts.api.module.match.market.internal.executor.model.MarketExecuteDataExchange;
import com.ts.api.module.match.market.internal.executor.model.MarketExecuteDataExchangeResult;
import com.ts.api.module.match.market.internal.executor.model.MarketExecuteFederate;
import com.ts.api.module.match.market.internal.executor.model.MarketExecuteFederateResult;
import com.ts.api.module.match.market.internal.executor.model.MarketExecuteTask;
import com.ts.api.module.match.market.internal.valid.model.ChannelMarketValidationResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 *  贷超-执行器
 *
 *  @author Pan
 */
@Component
public class MarketExecutorHandler {

    /** 全局超时时间 */
    private Integer globalHttpTimeout = 3000;

    @Autowired
    private MarketExecutorTaskHandler marketExecutorTaskHandler;
    @Autowired
    private ChannelLoginService channelLoginService;
    @Autowired
    private ChannelUserService channelUserService;
    @Autowired
    private ChannelFormService channelFormService;

    /**
     *  执行贷超撞库
     *
     *  @author Pan
     *  @param  marketExecuteDataExchange   执行器对象
     *  @return List
     */
    public List<MarketExecuteDataExchangeResult> executeDataExchange(MarketExecuteDataExchange marketExecuteDataExchange) {
        ChannelRequest channelRequest = marketExecuteDataExchange.getChannelRequest();
        List<ChannelMarketPO> listMarketValidate = marketExecuteDataExchange.getListMarketValidate();

        //  获取符合的贷超列表
        if (ValidParam.isEmpty(listMarketValidate)) {
            return Empty.list();
        }

        //  用户信息
        ChannelUserRegisterPO channelUserRegisterPO = null;
        List<ChannelUserFormFieldPO> listUserFormField = null;

        //  如果当前存在用户则获取用户信息
        boolean login = channelLoginService.isLogin();
        if (login) {
            ChannelCacheUser loginUser = channelLoginService.getLoginUser();
            Long userId = loginUser.getUserId();

            //  获取用户基本信息
            channelUserRegisterPO = channelUserService.get(ChannelUserQO.createUserId(userId));
            //  获取用户表单信息
            listUserFormField = channelFormService.listUserFormField(userId);
        }

        try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Callable<MarketExecuteDataExchangeResult>> callables = CollUtils.newArrayList(listMarketValidate.size());

            //  创建任务集
            for (ChannelMarketPO channelMarketPO : listMarketValidate) {
                //  创建任务id
                long reqId = IdUtils.snowFlakeId(8, 1);
                //  创建参数任务
                MarketExecuteTask executeTask = MarketExecuteTask.ofTask(channelRequest, channelMarketPO, globalHttpTimeout);
                executeTask.setChannelUserRegisterPO(channelUserRegisterPO);
                executeTask.setChannelUserFormPO(listUserFormField);
                executeTask.setReqId(reqId);
                //  提交撞库任务
                callables.add(marketExecutorTaskHandler.submitDataExchange(executeTask));
            }

            //  执行任务集
            List<MarketExecuteDataExchangeResult> listMatchResult = pool.invokeAll(callables, globalHttpTimeout - 200, TimeUnit.MILLISECONDS)
                .stream()
                .filter(future -> future.state() == Future.State.SUCCESS && ValidParam.isNotNull(future))
                .map(future -> future.resultNow())
            .toList();
            return listMatchResult;
        } catch (Exception e) {
            Log.get().error("{}", e.getMessage(), e);
        }
        return Empty.list();
    }

    /**
     *  执行贷超撞库依次/逐个匹配,返回单个匹配成功的贷超
     *
     *  @author Pan
     *  @param  marketExecuteDataExchange   执行器对象
     *  @return MarketExecuteDataExchangeResult
     */
    public MarketExecuteDataExchangeResult executeDataExchangeSequence(MarketExecuteDataExchange marketExecuteDataExchange) {
        ChannelRequest channelRequest = marketExecuteDataExchange.getChannelRequest();
        //  获取所有贷超验证成功列表
        List<ChannelMarketPO> listMarketValidate = marketExecuteDataExchange.getListMarketValidate();

        //  获取符合的贷超列表
        if (ValidParam.isEmpty(listMarketValidate)) {
            return new MarketExecuteDataExchangeResult();
        }

        //  用户信息
        ChannelUserRegisterPO channelUserRegisterPO = null;
        List<ChannelUserFormFieldPO> listUserFormField = null;

        //  如果当前存在用户则获取用户信息
        boolean login = channelLoginService.isLogin();
        if (login) {
            ChannelCacheUser loginUser = channelLoginService.getLoginUser();
            Long userId = loginUser.getUserId();

            //  获取用户基本信息
            channelUserRegisterPO = channelUserService.get(ChannelUserQO.createUserId(userId));
            //  获取用户表单信息
            listUserFormField = channelFormService.listUserFormField(userId);
        }

        //  获取已经首位排序过的贷超
        ChannelMarketPO marketSort = marketExecuteDataExchange.getMarketSort();

        //  匹配首位贷超流程
        {
            //  创建任务id
            long reqId = IdUtils.snowFlakeId(8, 1);
            //  创建参数任务
            MarketExecuteTask topExecuteTask = MarketExecuteTask.ofTask(channelRequest, marketSort, globalHttpTimeout);
            topExecuteTask.setChannelUserRegisterPO(channelUserRegisterPO);
            topExecuteTask.setChannelUserFormPO(listUserFormField);
            topExecuteTask.setReqId(reqId);

            //  执行撞库任务-匹配成功直接返回
            MarketExecuteDataExchangeResult topExecuteResult = marketExecutorTaskHandler.dataExchangeTask(topExecuteTask);
            if (topExecuteResult.getHasSuc()) {
                return topExecuteResult;
            }
        }

        //  匹配剩余贷超列表流程->直到有一个贷超返回成功为止
        {
            List<ChannelMarketPO> listMarketValidateCopy = CollUtils.copy(listMarketValidate);
            CollUtils.filter(listMarketValidateCopy, t -> t.getId().equals(marketSort.getId()));

            //  创建任务集
            for (ChannelMarketPO channelMarketPO : listMarketValidateCopy) {
                //  创建任务id
                long reqId = IdUtils.snowFlakeId(8, 1);
                //  创建参数任务
                MarketExecuteTask executeTask = MarketExecuteTask.ofTask(channelRequest, channelMarketPO, globalHttpTimeout);
                executeTask.setChannelUserRegisterPO(channelUserRegisterPO);
                executeTask.setChannelUserFormPO(listUserFormField);
                executeTask.setReqId(reqId);

                //  执行撞库任务
                MarketExecuteDataExchangeResult executeResult = marketExecutorTaskHandler.dataExchangeTask(executeTask);
                if (executeResult.getHasSuc()) {
                    return executeResult;
                }
            }
        }
        //  返回失败
        return new MarketExecuteDataExchangeResult();
    }

    /**
     *  执行贷超联登
     *
     *  @author Pan
     *  @param  marketExecuteFederate   执行器对象
     *  @return List
     */
    public MarketExecuteFederateResult executeFederate(MarketExecuteFederate marketExecuteFederate) {
        ChannelMarketPO channelMarketPO = marketExecuteFederate.getChannelMarket();
        Long userId = marketExecuteFederate.getUserId();
        ChannelRequest channelRequest = marketExecuteFederate.getChannelRequest();

        try {
            //  获取用户基本信息
            ChannelUserRegisterPO channelUserRegisterPO = channelUserService.get(ChannelUserQO.createUserId(userId));
            //  获取用户表单信息
            List<ChannelUserFormFieldPO> listUserFormField = channelFormService.listUserFormField(userId);

            //  创建任务id
            long reqId = IdUtils.snowFlakeId(8, 1);
            //  创建任务对象
            MarketExecuteTask executeTask = MarketExecuteTask.ofTask(channelRequest, channelMarketPO, globalHttpTimeout);
            executeTask.setChannelUserRegisterPO(channelUserRegisterPO);
            executeTask.setChannelUserFormPO(listUserFormField);
            executeTask.setReqId(reqId);

            //  发起联登任务
            MarketExecuteFederateResult marketExecuteFederateResult = marketExecutorTaskHandler.federateTask(executeTask);
            return marketExecuteFederateResult;
        } catch (Exception e) {
            Log.get().error("{}", e.getMessage(), e);
            //  返回失败
            MarketExecuteFederateResult marketExecuteFederateResult = new MarketExecuteFederateResult();
            marketExecuteFederateResult.setChannelMarket(channelMarketPO);
            marketExecuteFederateResult.setHasSuc(false);
            return marketExecuteFederateResult;
        }
    }

    /**
     *  执行贷超撞库->联登匹配
     *
     *  @param  channelMarketValidationResult   业务符合的渠道贷超列表
     *  @return List    返回所有成功联登的数据对象
     */
    public List<MarketExecuteFederateResult> executeUnion(ChannelMarketValidationResult channelMarketValidationResult) {
        ChannelRequest channelRequest = channelMarketValidationResult.getChannelRequest();

        //  获取符合的贷超列表
        List<ChannelMarketPO> listMarketValidate = channelMarketValidationResult.getListMarketValidate();
        if (ValidParam.isEmpty(listMarketValidate)) {
            return Empty.list();
        }

        //  如果当前用户信息
        ChannelCacheUser channelCacheUser = ChannelUserContext.get();
        Long userId = channelCacheUser.getUserId();

        //  获取用户基本信息
        ChannelUserRegisterPO channelUserRegisterPO = channelUserService.get(ChannelUserQO.createUserId(userId));
        //  获取用户表单信息
        List<ChannelUserFormFieldPO> listUserFormField = channelFormService.listUserFormField(userId);

        try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Callable<MarketExecuteFederateResult>> callables = CollUtils.newArrayList(listMarketValidate.size());

            //  创建任务集
            for (ChannelMarketPO channelMarketPO : listMarketValidate) {
                //  创建参数任务
                MarketExecuteTask executeTask = MarketExecuteTask.ofTask(channelRequest, channelMarketPO, globalHttpTimeout);
                executeTask.setChannelUserRegisterPO(channelUserRegisterPO);
                executeTask.setChannelUserFormPO(listUserFormField);
                //  提交撞库/联登任务
                callables.add(marketExecutorTaskHandler.submitUnion(executeTask));
            }

            //  执行任务集
            List<MarketExecuteFederateResult> listMatchResult = pool.invokeAll(callables, globalHttpTimeout - 200, TimeUnit.MILLISECONDS)
                .stream()
                .filter(future -> future.state() == Future.State.SUCCESS && ValidParam.isNotNull(future))
                .map(future -> future.resultNow())
            .toList();
            return listMatchResult;
        } catch (Exception e) {
            Log.get().error("{}", e.getMessage(), e);
        }
        return Empty.list();
    }
}
